﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reactive.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IdComLog.Reactive
{
    /// <summary>
    /// Provides utility methods for working with SQL Server.
    /// </summary>
    public static class SqlClient
    {
        /// <summary>
        /// Watches the results of a SqlCommand for changes.
        /// </summary>
        /// <param name="cmd">The command to watch.</param>
        /// <returns>An observable of changes.</returns>
        public static IObservable<SqlNotificationEventArgs> Watch(this SqlCommand cmd)
        {
            Contract.Requires(cmd != null);
            Contract.Ensures(Contract.Result<IObservable<SqlNotificationEventArgs>>() != null);

            SqlDependency dep = new SqlDependency(cmd);

            return Observable.FromEvent<OnChangeEventHandler, SqlNotificationEventArgs>(a => ((OnChangeEventHandler)((s, ea) => a(ea))),
                eh => { dep.OnChange += eh; },
                eh => { dep.OnChange -= eh; });
        }
    }
}
